package com.xxl.job.admin.core.alarm.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.alarm.utils.DingUtils;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


/**
 * job alarm by email
 *
 * @author xuxueli 2020-01-19
 */
@Component
public class DingJobAlarm implements JobAlarm {
    private static Logger logger = LoggerFactory.getLogger(DingJobAlarm.class);
    //发送的json格式
    private static String json="{\n" +
            "    \"msgtype\": \"text\", \n" +
            "    \"text\": {\n" +
            "        \"content\": \"\"\n" +
            "    }, \n" +
            "    \"at\": {\n" +
            "        \"atMobiles\": [\n" +
            "        ], \n" +
            "        \"isAtAll\": false\n" +
            "    }\n" +
            "}";
    /**
     * fail alarm
     *
     * @param jobLog
     */
    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;
        //如果email的位置是f 则不提醒
        if ("f".equals(info.getAlarmEmail().trim())){
            return alarmResult;
        }

        //将一些无用标签去掉
        //调用失败
        String replace=null;
        replace+= jobLog.getTriggerMsg().replace("<br>", "\n" )
                .replace("<span style=\"color:#00c0ef;\" >","")
                .replace("</span>","");

        //执行失败
        if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
            replace = replace.split(">>>>>>>>>>>触发调度<<<<<<<<<<< ")[0];
            replace+="\n 执行失败情况："+jobLog.getHandleMsg();
        }

        //拿到执行器
        XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao().load(Integer.valueOf(info.getJobGroup()));

        replace="执行器："+group.getTitle()+"\n"
                +"appName："+group.getAppName()+"\n"
        +"任务描述："+info.getJobDesc()+"\n"
        +"任务负责人："+info.getAuthor()+"\n"
        + "任务参数："+info.getExecutorParam()+"\n"
        +"任务类型："+info.getGlueType()+"\n"+replace;


        JSONObject alarm = JSONObject.parseObject(json);
        JSONObject text = alarm.getJSONObject("text");
        text.put("content","定时任务 \n"+I18nUtil.getString("jobconf_monitor")+"\n"+replace);

        //如果不为空 则@一个人
        if (info!=null &&info.getAlarmEmail()!=null&&info.getAlarmEmail().trim().length()>0){
            JSONObject at = alarm.getJSONObject("at");
            JSONArray atMobiles = at.getJSONArray("atMobiles");
            String[] split = info.getAlarmEmail().trim().split(";");
            for (String s : split) {
                atMobiles.add(s);
            }
        }


        String jsonString = JSONObject.toJSONString(alarm);

            // 发送预警消息
            try {
                //System.out.println(jsonString);
               DingUtils.alarm(jsonString);

            } catch (Exception e) {
                logger.error(">>>>>>>>>>> xxl-job, job fail alarm email send error, JobLogId:{}", jobLog.getId(), e);
                alarmResult = false;
            }


        return alarmResult;
    }


}
